<!DOCTYPE html>
<html>
    <head>
        <!-- 页面meta -->
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>传智健康</title>
        <meta name="description" content="传智健康">
        <meta name="keywords" content="传智健康">
        <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <!-- 引入样式 -->
        <link rel="stylesheet" href="../plugins/elementui/index.css">
        <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
        <link rel="stylesheet" href="../css/style.css">
        <!-- 引入组件库 -->
        <script type="text/javascript" src="../js/jquery.min.js"></script>
        <script src="../js/vue.js"></script>
        <script src="../plugins/elementui/index.js"></script>
        <script src="../js/axios-0.18.0.js"></script>
        <script src="//libs.baidu.com/jquery/1.9.0/jquery.js"></script>
        <script src="https://unpkg.com/vue-baidu-map"></script>
        <style>
            .avatar-uploader .el-upload {
                border: 1px dashed #d9d9d9;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
            }
            .avatar-uploader .el-upload:hover {
                border-color: #409EFF;
            }
            .avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 178px;
                height: 178px;
                line-height: 178px;
                text-align: center;
            }
            .avatar {
                width: 178px;
                height: 178px;
                display: block;
            }
            .datatable {
                position: relative;
                box-sizing: border-box;
                -webkit-box-flex: 1;
                width: 100%;
                max-width: 100%;
                font-size: 14px;
                color: rgb(96, 98, 102);
                overflow: hidden;
                flex: 1 1 0%;
            }
            .datatable td, .datatable th {
                padding: 12px 0;
                min-width: 0;
                -webkit-box-sizing: border-box;
                box-sizing: border-box;
                text-overflow: ellipsis;
                vertical-align: middle;
                position: relative;
                text-align: left;
            }
            .bm-view {width: 100%; height: 200px}
        </style>
    </head>
    <body class="hold-transition">
    <div id="app">
        <!--百度地图容器-->
            <div class="content-header">
                <h1>体检机构管理<small>体检机构地址管理</small></h1>
                <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>体检机构管理</el-breadcrumb-item>
                    <el-breadcrumb-item>体检机构地址管理</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="app-container">
                <div class="box">
                    <div class="filter-container">
                        <el-input placeholder="体检机构名" v-model="pagination.queryString" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"></el-input>
                        <el-button @click="findPage()" class="dalfBut">查询</el-button>
                        <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
                    </div>
                    <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
                        <el-table-column type="index" align="center" label="序号"></el-table-column>
                        <el-table-column prop="organName" label="体检机构名" align="center"></el-table-column>
                        <el-table-column prop="phone" label="联系电话" align="center"></el-table-column>
                        <el-table-column prop="lng,lat" label="经纬度" align="center" >
                            <template slot-scope="scope">
                                {{scope.row.lng}},{{scope.row.lat}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="organPic" label="机构图片" align="center"></el-table-column>
                        <el-table-column prop="address" label="详细地址" align="center"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination-container">
                        <el-pagination
                            class="pagiantion"
                            @current-change="handleCurrentChange"
                            :current-page="pagination.currentPage"
                            :page-size="pagination.pageSize"
                            layout="total, prev, pager, next, jumper"
                            :total="pagination.total">
                        </el-pagination>
                    </div>
                    <!-- 新增标签弹层 -->
                    <div class="add-form">
                        <el-dialog title="新增体检机构地址" :visible.sync="dialogFormVisible">
                            <template>
                                <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="体检机构名" prop="organName">
                                                <el-input v-model="formData.organName"/>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="联系电话" >
                                                <el-input v-model="formData.phone"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="上传体检机构图片">
                                                <!--
                                                el-upload：上传组件
                                                action：上传的提交地址
                                                auto-upload：选中文件后是否自动上传
                                                name：上传文件的名称，服务端可以根据名称获得上传的文件对象
                                                show-file-list：是否显示已上传文件列表
                                                on-success：文件上传成功时的钩子
                                                before-upload：上传文件之前的钩子
                                                -->
                                                <el-upload
                                                  class="avatar-uploader"
                                                  action="/organAddress/upload.do"
                                                  :auto-upload="autoUpload"
                                                  name="imgFile"
                                                  :show-file-list="false"
                                                  :on-success="handleAvatarSuccess"
                                                  :before-upload="beforeAvatarUpload">
                                                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                                </el-upload>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="经纬度">
                                                <el-input v-model="formData.coordinate"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="详细地址">
                                                <el-input v-model="formData.address"/>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item >
                                                <el-button type="primary" icon="el-icon-location" @click="showMap">设置定位</el-button>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                                <!--百度地图容器-->
                                <baidu-map class="bm-view" v-show="mapVisible" :center="center" :zoom="zoom" @ready="handler"></baidu-map>
                            </template>
                            <div slot="footer" class="dialog-footer">
                                <el-button @click="dialogFormVisible = false">取消</el-button>
                                <el-button type="primary" @click="handleAdd()">确定</el-button>
                            </div>
                        </el-dialog>
                    </div>

                    <!-- 编辑标签弹层 -->
                    <div class="add-form">
                        <el-dialog title="编辑检查组" :visible.sync="dialogFormVisible4Edit">
                            <template>
                                <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="体检机构名" prop="organName">
                                                <el-input v-model="formData.organName"/>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="联系电话" >
                                                <el-input v-model="formData.phone"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="上传体检机构图片">
                                                <!--
                                                el-upload：上传组件
                                                action：上传的提交地址
                                                auto-upload：选中文件后是否自动上传
                                                name：上传文件的名称，服务端可以根据名称获得上传的文件对象
                                                show-file-list：是否显示已上传文件列表
                                                on-success：文件上传成功时的钩子
                                                before-upload：上传文件之前的钩子
                                                -->
                                                <el-upload
                                                  class="avatar-uploader"
                                                  action="/organAddress/upload.do"
                                                  :auto-upload="autoUpload"
                                                  name="imgFile"
                                                  :show-file-list="false"
                                                  :on-success="handleAvatarSuccess"
                                                  :before-upload="beforeAvatarUpload">
                                                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                                </el-upload>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="经纬度">
                                                <el-input v-model="formData.coordinate"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="详细地址">
                                                <el-input v-model="formData.address"/>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item >
                                                <el-button type="primary" icon="el-icon-location" @click="showMap">设置定位</el-button>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                                <baidu-map class="bm-view" v-if="mapVisible" :center="center" :zoom="zoom" @ready="handler"></baidu-map>
                            </template>
                            <div slot="footer" class="dialog-footer">
                                <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
                                <el-button type="primary" @click="handleEdit()">确定</el-button>
                            </div>
                        </el-dialog>
                    </div>
                </div>
            </div>
        </div>
    </body>

    <script>
        Vue.use(VueBaiduMap.default, {
            ak: 'cyxF4CKA16WjQ21otdkhCAcKNAmPi5UA',
        })
        var vue = new Vue({
            el: '#app',
            data:{
                autoUpload:true,//自动上传
                imageUrl:null,//模型数据，用于上传图片完成后图片预览
                pagination: {//分页相关属性
                    currentPage: 1,
                    pageSize:10,
                    total:100,
                    queryString:null,
                },
                dataList: [],//列表数据
                formData: {
                    coordinate: ""
                },//表单数据
                tableData:[],//新增和编辑表单中对应的检查项列表数据
                dialogFormVisible: false,//控制添加窗口显示/隐藏
                dialogFormVisible4Edit:false,//控制编辑窗口显示/隐藏
                rules: {//校验规则
                    organName: [{ required: true, message: '体检机构名为必填项', trigger: 'blur' }]
                },
                mapVisible: false,
                center: {
                    lng: 0, lat: 0
                },
                zoom: 3,
                map: {},
                BMap:{},
                rowId: -1,
                isEdit: false, // 判断是新建还是编辑，用来获取坐标 新增根据浏览器地址，编辑根据用户的坐标
                loadCoordinate: {lng: '', lat: ''},
            },
            created() {
                this.findPage();
            },
            methods: {
                // 设置定位
                showMap({BMap, map}) {
                    console.log(BMap, map)
                    console.log(this.rowId>0?"编辑":"新增")
                    this.mapVisible = true;
                    // this.map = map;
                    BMap = this.BMap;
                    let x;
                    let y;
                    x = this.formData.coordinate.split(",")[0];
                    y = this.formData.coordinate.split(",")[1];
                    this.formData.lng = x;
                    this.formData.lat = y;
                    console.log(x);
                    console.log(y);
                    this.map.centerAndZoom(new BMap.Point(x,y), 15);
                },
                handler({BMap, map}) {
                    this.mapVisible = true;
                    console.log(BMap, map)
                    this.map = map;
                    this.BMap = BMap;
                    this.map.centerAndZoom(new BMap.Point(this.formData.lng | 116.417854, this.formData.lat | 39.921988), 15);
                    this.map.enableScrollWheelZoom(true);
                    // var data_info = [[116.417854,39.921988,"地址：北京市东城区王府井大街88号乐天银泰百货八层"],
                    //     [116.406605,39.921585,"地址：北京市东城区东华门大街"],
                    //     [116.412222,39.912345,"地址：北京市东城区正义路甲5号"]
                    // ];
                    // var opts = {
                    //     width : 250,     // 信息窗口宽度
                    //     height: 80,     // 信息窗口高度
                    //     title : "信息窗口" , // 信息窗口标题
                    //     enableMessage:true//设置允许信息窗发送短息
                    // };
                    // for(var i=0;i<data_info.length;i++){
                    //     var marker = new BMap.Marker(new BMap.Point(data_info[i][0],data_info[i][1]));  // 创建标注
                    //     var content = data_info[i][2];
                    //     this.map.addOverlay(marker);               // 将标注添加到地图中
                    //     this.addClickHandler(content,marker,opts);
                    // }
                    var that = this;
                    if (!this.isEdit) {
                        //根据网络地址获取ip
                        var geolocation = new BMap.Geolocation();
                        console.log("修改位置前：",that.formData.coordinate);
                        geolocation.getCurrentPosition(function(r){
                            var mk = new BMap.Marker(r.point);
                            console.log("my loc:", mk)
                            that.map.enableScrollWheelZoom(true);
                            // that.map.addOverlay(mk);
                            that.map.panTo(r.point);
                            that.formData.coordinate = r.point.lng + ',' + r.point.lat;
                            that.loadCoordinate = r.point;
                            that.coordinateToLngLat(that.formData.coordinate, that.formData)
                            console.log("修改位置后：",that.formData.coordinate);
                        },{enableHighAccuracy: true});
                    }else {
                        this.map.centerAndZoom(new BMap.Point(this.formData.lng,this.formData.lat), 15);
                    }
                    function showInfo(e){
                        // alert(e.point.lng + ", " + e.point.lat);
                        that.formData.coordinate = e.point.lng + "," +e.point.lat;
                        that.coordinateToLngLat(that.formData.coordinate, that.formData)
                    }
                    map.addEventListener("click",showInfo)
                },
                // addClickHandler(content,marker,opts){
                //     let that = this;
                //     marker.addEventListener("click",function(e){
                //         that.openInfo(content,e,opts)}
                //     );
                // },
                // openInfo(content,e,opts){
                //     var p = e.target;
                //     var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
                //     var infoWindow = new BMap.InfoWindow(content,opts);  // 创建信息窗口对象
                //     this.map.openInfoWindow(infoWindow,point); //开启信息窗口
                // },
                //文件上传成功后的钩子，response为服务端返回的值，file为当前上传的文件封装成的js对象
                handleAvatarSuccess(response, file) {
                    this.imageUrl = "http://qck660xrh.bkt.clouddn.com/"+response.data;
                    console.log("imageUrl-----", this.imageUrl)
                    this.$message({
                        message: response.message,
                        type: response.flag ? 'success' : 'error'
                    });
                    this.formData.organPic = response.data;
                },
                // 将经纬度转为经度 纬度
                coordinateToLngLat(coordinate, formData) {
                    let x = coordinate.split(",")[0];
                    let y = coordinate.split(",")[1];
                    formData.lng = x;
                    formData.lat = y;
                },
                //上传图片之前执行
                beforeAvatarUpload(file) {
                    const isJPG = file.type === 'image/jpeg';
                    const isLt2M = file.size / 1024 / 1024 < 2;
                    if (!isJPG) {
                        this.$message.error('上传套餐图片只能是 JPG 格式!');
                    }
                    if (!isLt2M) {
                        this.$message.error('上传套餐图片大小不能超过 2MB!');
                    }
                    return isJPG && isLt2M;
                },
                //编辑
                handleEdit() {
                    //校验表单输入项是否合法
                    this.$refs['dataAddForm'].validate((valid) => {
                        if (valid) {
                            //发送ajax请求，提交模型数据
                            axios.post("/organAddress/edit.do", this.formData).
                            then((response)=> {
                                //隐藏编辑窗口
                                this.dialogFormVisible4Edit = false;
                                if(response.data.flag){
                                    this.$message({
                                        message: response.data.message,
                                        type: 'success'
                                    });
                                }else{
                                    this.$message.error(response.data.message);
                                }
                            }).finally(()=> {
                                this.findPage();
                            });
                        }
                    });
                    this.mapVisible = false;
                },
                //添加
                handleAdd () {
                    //校验表单输入项是否合法
                    this.$refs['dataAddForm'].validate((valid) => {
                        if (valid) {
                            //表单数据校验通过，发送ajax请求将模型数据提交到后台处理
                            axios.post("/organAddress/add.do" , this.formData)
                                .then((response)=> {
                                    //关闭新增窗口
                                    this.dialogFormVisible = false;
                                    if(response.data.flag){
                                        //新增成功，弹出成功提示
                                        this.$message({
                                            message: response.data.message,
                                            type: 'success'
                                        });
                                    }else{
                                        //新增失败，弹出错误提示
                                        this.$message.error(response.data.message);
                                    }
                                }).finally(()=> {
                                this.findPage();
                            });
                        }
                    });
                    this.mapVisible = false;
                },
                //分页查询
                findPage() {
                    //分页参数
                    var param = {
                        currentPage:this.pagination.currentPage,//页码
                        pageSize:this.pagination.pageSize,//每页显示的记录数
                        queryString:this.pagination.queryString//查询条件
                    };
                    //请求后台
                    axios.post("/organAddress/findPage.do",param).then((response)=> {
                        //为模型数据赋值，基于VUE的双向绑定展示到页面
                        this.dataList = response.data.rows;
                        console.log(this.dataList);

                        this.pagination.total = response.data.total;
                    });
                },
                // 重置表单
                resetForm() {
                    this.formData = {
                        coordinate: "",
                    };
                },
                // 弹出添加窗口
                handleCreate() {
                    this.resetForm();
                    this.isEdit = false;
                    this.dialogFormVisible = true;
                    this.mapVisible = true;
                    this.rowId = -1;
                    console.log(this.loadCoordinate)
                    if (this.loadCoordinate && this.loadCoordinate.lng.length>0) {
                        // this.map.centerAndZoom(new BMap.Point(this.formData.lng,this.formData.lat), 15);
                        this.formData.coordinate = this.loadCoordinate.lng + ',' + this.loadCoordinate.lat;
                        this.formData.lng = this.loadCoordinate.lng;
                        this.formData.lat = this.loadCoordinate.lat;
                    }
                },
                // 弹出编辑窗口
                handleUpdate(row) {
                    this.isEdit = true;
                    //发送ajax请求根据id查询检查组信息，用于基本信息回显
                    axios.get("/organAddress/findById.do?id=" + row.id).then((res)=>{
                        if(res.data.flag){
                            //弹出编辑窗口
                            this.dialogFormVisible4Edit = true;
                            this.mapVisible = true;
                            this.rowId = row.id;
                            //为模型数据赋值，通过VUE数据双向绑定进行信息的回显
                            this.formData = res.data.data;
                            this.formData.coordinate = this.formData.lng+","+this.formData.lat;
                            if (this.formData.organPic != null) {
                                this.imageUrl = "http://qck660xrh.bkt.clouddn.com/"+this.formData.organPic;
                            }else {
                                this.imageUrl = "";
                            }
                            // console.log("编辑地址请求经纬度之后：",this.BMap)
                            this.map.centerAndZoom(new BMap.Point(this.formData.lng,this.formData.lat), 15);
                            //发送ajax请求查询所有的检查项信息，用于检查项表格展示
                            axios.get("/organAddress/findAll.do").then((res)=> {
                                if(res.data.flag){
                                    //为模型数据赋值，通过VUE数据双向绑定进行信息的回显
                                    this.tableData = res.data.data;
                                }else{
                                    this.$message.error(res.data.message);
                                }
                            });
                        }else{
                            this.$message.error("获取数据失败，请刷新当前页面");
                        }
                    });
                },
                //切换页码
                handleCurrentChange(currentPage) {
                    //currentPage为切换后的页码
                    this.pagination.currentPage = currentPage;
                    this.findPage();
                },
                // 删除
                handleDelete(row) {
                    this.$confirm("确认删除当前选中记录吗？","提示",{type:'warning'}).then(()=>{
                    //发送ajax请求根据id查询检查组信息，用于基本信息回显
                        axios.get("/organAddress/deleteById.do?id=" + row.id).then((res)=>{
                            if(res.data.flag) {
                                //弹出成功提示信息
                                this.$message({
                                    type: 'success',
                                    message: res.data.message
                                });
                                //重新进行分页查询
                                this.findPage();
                            } else {
                            //执行失败
                            this.$message.error(res.data.message);
                        }
                        }).catch((r)=>{
                            this.showMessage(r);
                        });
                    });
                },
                //权限不足提示
                showMessage(r){
                    if(r == 'Error: Request failed with status code 403'){
                        //权限不足
                        this.$message.error('无访问权限');
                        return;
                    }else{
                        this.$message.error('未知错误');
                        return;
                    }
                }
            }
        })
    </script>
</html>
